﻿namespace com.savealot.Extensions.SharePointExtensions
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;

    using Microsoft.SharePoint;

    public static class SPListExtensions
    {
        #region Methods

        public static SPView CreateView( this SPList spList, string viewTitle, List<string> viewFields, string query, uint rowLimit, bool paged, bool makeViewDefault, SPViewCollection.SPViewType viewType, bool replaceExisting )
        {
            return spList.CreateView( viewTitle, viewTitle, viewFields, query, rowLimit, paged, makeViewDefault, viewType, replaceExisting );
        }

        public static SPView CreateView( this SPList spList, string rootUrlName, string viewTitle, List<string> viewFields, string query, uint rowLimit, bool paged, bool makeViewDefault, SPViewCollection.SPViewType viewType, bool replaceExisting )
        {
            SPView v = null;
            foreach ( SPView spView in spList.Views )
            {
                if ( spView.ToString( ).Equals( viewTitle, StringComparison.OrdinalIgnoreCase ) )
                {
                    v = spView;
                    break;
                }
            }
            if ( v != null && replaceExisting )
                spList.Views.Delete( v.ID );
            else if ( v != null && !replaceExisting )
                return v;

            StringCollection vf = new StringCollection( );
            vf.AddRange( viewFields.ToArray( ) );
            v = spList.Views.Add( rootUrlName, vf, query, rowLimit, paged, makeViewDefault, viewType, false );
            v.Title = viewTitle;
            spList.Update( );
            return v;
        }

        #endregion Methods
    }
}